package com.informationsystem.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.informationsystem.service.AttachementManager;
import com.informationsystem.service.NoticeManager;
import com.informationsystem.dao.SearchException;
import com.informationsystem.model.Attachement;
import com.informationsystem.webapp.action.BaseAction;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.struts2.ServletActionContext;

public class AttachementAction extends BaseAction implements Preparable {
    private AttachementManager attachementManager;
    private NoticeManager noticeManager;
    private List attachements;
    private Attachement attachement;
    private Long id;
    private String query;
    private File attachmentfile;
    private String contentType;
    private String filename;

    public void setAttachementManager(AttachementManager attachementManager) {
        this.attachementManager = attachementManager;
    }

    public List getAttachements() {
        return attachements;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String attachementId = getRequest().getParameter("attachement.id");
            if (attachementId != null && !attachementId.equals("")) {
                attachement = attachementManager.get(new Long(attachementId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        try {
            attachements = attachementManager.search(query, Attachement.class);
        } catch (SearchException se) {
            addActionError(se.getMessage());
            attachements = attachementManager.getAll();
        }
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Attachement getAttachement() {
        return attachement;
    }

    public void setAttachement(Attachement attachement) {
        this.attachement = attachement;
    }

    public String delete() {
    	attachement = attachementManager.get(attachement.getId());
    	File file = new File(ServletActionContext.getServletContext().getRealPath("/upload")+"\\"+attachement.getNotice().getId()+"_" + attachement.getFilename());
    	file.delete();
        attachementManager.remove(attachement.getId());
        saveMessage(getText("attachement.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            attachement = attachementManager.get(id);
        } else {
            attachement = new Attachement();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (attachement.getId() == null);

        if(isNew){
        	attachement.setFilename(filename);
            try {
    			saveFile(attachement.getNotice().getId()+"_"+filename, attachmentfile);
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
        }
        
        attachementManager.save(attachement);

        String key = (isNew) ? "attachement.added" : "attachement.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }

    public void saveFile(String tosavefilename, File tosavefile) throws IOException{
		String path = ServletActionContext.getServletContext().getRealPath("/upload");
		File f = new File(path);
        if(!f.exists()){
            f.mkdir(); 
        }     
        FileOutputStream fos = new FileOutputStream(ServletActionContext.getServletContext().getRealPath("/upload")+"\\"+tosavefilename);
        InputStream is = new FileInputStream(tosavefile);
        byte[] buffer = new byte[8192];
        int count = 0;
        while ((count = is.read(buffer)) > 0) {
            fos.write(buffer, 0, count);
    	}
        fos.flush();
    	fos.close();
    	is.close();
    }
    
	public NoticeManager getNoticeManager() {
		return noticeManager;
	}

	public void setNoticeManager(NoticeManager noticeManager) {
		this.noticeManager = noticeManager;
	}
	
	public List getNoticeList(){
		return noticeManager.getAll();
	}
	
	public File getAttachmentfile() {
		return attachmentfile;
	}

	public void setAttachmentfile(File attachmentfile) {
		this.attachmentfile = attachmentfile;
	}
	

    public void setAttachmentfileContentType(String contentType) {
       this.contentType = contentType;
    }

    public void setAttachmentfileFileName(String filename) {
       this.filename = filename;
    }
}